//
//  SQWeiboHttpManager.swift
//  SwiftWeibo
//
//  Created by suqianghotel on 16/11/28.
//  Copyright © 2016年 suqianghotel. All rights reserved.
//

import UIKit
import Alamofire
import YYModel


extension SQHttpManager {
    
    public var logon: Bool {
        return   access_token != nil
    }
    
//    access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
//    count	false	int	单页返回的记录条数，默认为50。
//    page	false	int	返回结果的页码，默认为1。
//    base_app	false	int	是否只获取当前应用的数据。0为否（所有数据），1为是（仅当前应用），默认为0。
    open func status_public_timeline(success:@escaping ( _ data:[[String:AnyObject]]?)->Void, failure:(_ msg:String, _ code:String)->Void)
    {
        
        let params = [
                      "count":"50",
                      "page":"1",
                      "base_app":"0"]
        
        
        commonRequest(url: "https://api.weibo.com/2/statuses/public_timeline.json",
                method: .get,
                params: params,
                headers: nil,
                success: {
                    
                (data) in
                    
                    
                    if let statusList = data as? [String:AnyObject]
                    {
                        success(statusList["statuses"] as? [[String:AnyObject]])
                    }
                    else
                    {
                        success([[String:AnyObject]]())
                    }
                    
                    
                },
                failure: failure)
    }
    
    
    
//    access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
//    since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
//    max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
//    count	false	int	单页返回的记录条数，最大不超过100，默认为20。
//    page	false	int	返回结果的页码，默认为1。
//    base_app	false	int	是否只获取当前应用的数据。0为否（所有数据），1为是（仅当前应用），默认为0。
//    feature	false	int	过滤类型ID，0：全部、1：原创、2：图片、3：视频、4：音乐，默认为0。
//    trim_user	false	int	返回值中user字段开关，0：返回完整user字段、1：user字段仅返回user_id，默认为0。
    open func status_home_timeline(since_id: Int64, max_id: Int64, success:@escaping ( _ data:[[String:AnyObject]]?)->Void, failure:(_ msg:String, _ code:String)->Void)
    {
        
        let params = [
            "since_id":"\(since_id)",
            "max_id":"\(max_id > 0 ? max_id - 1: 0)",
            "count":"20"]
        
        commonRequest(url: "https://api.weibo.com/2/statuses/home_timeline.json",
                      method: .get,
                      params: params,
                      headers: nil,
                      success: {
                        
                        (data) in
                        
                        if let statusList = data as? [String:AnyObject]
                        {
                            success(statusList["statuses"] as? [[String:AnyObject]])
                        }
                        else
                        {
                            success([[String:AnyObject]]())
                        }
                        
                        
        },
                      failure: failure)
    }
    
    
    public func remind_unread_count(success:@escaping ( _ data:SQUnread?)->Void, failure:(_ msg:String, _ code:String)->Void)
    {
        let url = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        commonRequest(url: url,
                      method: .get,
                      params: ["uid":self.uid!],
                      headers: nil,
                      success: { (data) in

                        if let unread = SQUnread.yy_model(with: (data as? [String:AnyObject]) ?? [:])
                        {
                            success(unread)
                        }
                        else
                        {
                            success(SQUnread())
                        }
                        
                        
        },
                      failure: failure)
    }
    
    
   
    
    open func commonRequest(url:String,
                            method:HTTPMethod = .get,
                            params:[String:String]?=nil,
                            headers:[String:String]?=nil,
                            success:@escaping (_ data:Any?)->Void,
                            failure:(_ msg:String, _ code:String)->Void)
    {
        
        var params = params
        
        if params == nil {
            params = [String:String]()
        }
        
        params!["access_token"] = access_token
    
        request(url: url, method: method, params: params, headers: headers, success: success, failure: failure);
    }
    

}

/// MARK: 授权以及用户信息相关
extension SQHttpManager
{
    
    // 拉取access_token后，获取用户信息
    open func loadAccessToken(with code: String, completion:@escaping (_ isSuccess: Bool)->Void)
    {
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":client_id,
                      "client_secret":client_secret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":redirect_uri]
        
        SQHttpManager.shared.post(url: url, params: params, success: { data in
            
            if let dict = data as? [String:AnyObject]{
                
                SQUserAccountManager.shared.userInfo = SQUserModel.yy_model(with: dict)
                
                guard
                    let access_token = SQUserAccountManager.shared.userInfo?.access_token,
                    let uid = SQUserAccountManager.shared.userInfo?.uid
                else {
                    completion(false)
                    return;
                }
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: SQUserDidLoginNotification), object: nil, userInfo: nil)
                
                /// 拉取用户信息
                self.loadUserInfo(with:access_token, uid: uid)

                completion(true)
                
            }
            else
            {
                completion(false)
            }
            
        }, failure: { (msg, code) in
            completion(false)
        })
    }
    
    
    open func loadUserInfo(with accessToken:String, uid:String){
        
        
        let url = "https://api.weibo.com/2/users/show.json"
        let params = ["access_token":accessToken,
                      "uid":uid]
        
        
        SQHttpManager.shared.request(url: url, params: params, success: { data in
            
            if let dict = data as? [String:AnyObject]{
                
                SQUserAccountManager.shared.userInfo?.yy_modelSet(with: dict);
                SQUserAccountManager.shared.synchronize()
            }
            else
            {

            }
            
        }, failure: { (msg, code) in

        })
        
    }
    
    
    
    
}
